package com.hospital.controller;

import com.hospital.model.Appointment;
import com.hospital.service.BookingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/bookings")
public class BookingController {

    private final BookingService bookingService;

    // 构造函数注入（推荐方式）
    @Autowired
    public BookingController(BookingService bookingService) {
        this.bookingService = bookingService;
    }

    /**
     * 创建预约（兼容原有控制台调用方式）
     */
    @PostMapping
    public ResponseEntity<Appointment> createBooking(
            @RequestParam Long doctorId,
            @RequestParam Long patientId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime dateTime) {

        try {
            Appointment appointment = bookingService.bookAppointment(doctorId, patientId, dateTime);
            return ResponseEntity.ok(appointment);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 取消预约（对应原有cancelAppointment功能）
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<String> cancelBooking(@PathVariable Long id) {
        try {
            bookingService.cancelAppointment(id);
            return ResponseEntity.ok("Appointment cancelled");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 获取医生所有预约（对应原有getDoctorAppointments功能）
     */
    @GetMapping("/doctor/{doctorId}")
    public List<Appointment> getDoctorBookings(@PathVariable Long doctorId) {
        return bookingService.getDoctorAppointments(doctorId);
    }

    /**
     * 兼容原有控制台调用的快捷方法（可选）
     */
    @GetMapping("/legacy-compat")
    public String legacyCompatibility(
            @RequestParam(required = false) Long doctorId,
            @RequestParam(required = false) Long patientId,
            @RequestParam(required = false) String action) {

        // 保持对原有控制台调用的兼容
        if ("cancel".equals(action)) {
            bookingService.cancelAppointment(patientId); // 这里用patientId模拟原参数
            return "Cancelled via legacy interface";
        }
        return "Legacy interface is available";
    }
}